#encoding:utf8

import sys
import math
import numpy as np

try:
	from OpenGL.GLUT import *
	from OpenGL.GL import *
	from OpenGL.GLU import *
except:
	print '''
ERROR: PyOpenGL not installed properly.  
		'''

s_eye	= [0, 0, 50]
s_at	= [0, 0, 0]
s_angle	= -90

class Camera(object):
	def __init__(self):
		self.position	= np.array((0, 0, 0))
		self.direction	= np.array((0, 0, 1))
		self.up			= np.array((0, 1, 0))
		self.right		= np.array((1, 0, 0))
	
	def walk(self, units):
		self.position	+= self.direction * units
	
	def strafe(self, units):
		self.position	+= self.right * units

	def fly(self, units):
		self.position	+= self.up * units
	
	def pitch(self, angle):
		pass

	def tick(self):
		glPushMatrix()
		glLoadIdentity()
		glTranslatef(self.position[0], self.position[1], self.position[1])
		glRotatef(self.direction[0], 1, 0, 0)
		glRotatef(self.direction[1], 0, 1, 0)
		glRotatef(self.direction[2], 0, 0, 1)

def init(): 
	glClearColor (0.0, 0.0, 0.0, 0.0)
	glClearDepth(1.0)
	glShadeModel (GL_SMOOTH)

def display():
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

	glColor3f (1.0, 1.0, 1.0)
	glLoadIdentity ()			 # clear the matrix 
	global s_angle, s_eye, s_at
	gluLookAt(s_eye[0], s_eye[1], s_eye[2], s_at[0], s_at[1], s_at[2], 0, 1, 0)

	# viewing transformation 

	glScalef (1.0, 2.0, 1.0)		 # modeling transformation 
	glutWireCube (1.0)

	glBegin(GL_LINES)
	xMax	= 10
	yMax	= 10
	for x in xrange(-xMax, xMax + 1):
		glVertex3f(x, -yMax, 0)
		glVertex3f(x, yMax, 0)

	for y in xrange(-yMax, yMax + 1):
		glVertex3f(-xMax, y, 0)
		glVertex3f(xMax, y, 0)

	glEnd()


	glutSwapBuffers()

def reshape (width, height):
	width	= width or 1
	height	= height or 1
	glViewport (0, 0, width, height)

	glMatrixMode (GL_PROJECTION)
	glLoadIdentity ()
	# glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)
	gluPerspective(60, width/height, 1.0, 100)
	glMatrixMode (GL_MODELVIEW)

def keyboard(key, x, y):
	escape	= chr(27)
	if key == escape:
		sys.exit(0)
	
	key	= key.upper()
	global s_angle, s_eye, s_at

	delta	= 2
	if key == 'A':
		s_angle	-= delta
	elif key == 'D':
		s_angle	+= delta
	
	rad	= math.pi * s_angle / 180

	speed	= 1.0
	if key == 'W':
		s_eye[2]	+= math.sin(rad) * speed
		s_eye[0]	+= math.cos(rad) * speed

	elif key == 'S':
		s_eye[2]	-= math.sin(rad) * speed
		s_eye[0]	-= math.cos(rad) * speed

	s_at[0]	= s_eye[0] + 100 * math.cos(rad)
	s_at[2]	= s_eye[2] + 100 * math.sin(rad)
	s_at[1]	= s_eye[1]

glutInit(sys.argv)
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB)
glutInitWindowSize (500, 500)
glutInitWindowPosition (100, 100)
glutCreateWindow ('cube')
init ()
glutDisplayFunc(display)
glutIdleFunc(display)
glutReshapeFunc(reshape)
glutKeyboardFunc(keyboard)
glutMainLoop()
